package com.ycl.javacore.consistenthash;

import java.util.LinkedList;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * User: OF1089 杨成龙
 * Date: 2020/3/12
 * Time: 10:47 上午
 * Desc: 一致性hash算法，采用虚拟节点
 */
public class ConsistentHashTwo {

    //待添加入Hash环的服务器列表
    private static String[] servers = {"192.168.0.1:8080", "192.168.0.2:8080",
            "192.168.0.3:8080", "192.168.0.4:8080", "192.168.0.5:8080"};
    //存放真是服务器节点
    private static LinkedList<String> realNodes = new LinkedList<>();

    private static SortedMap<Integer, String> virtualNodes = new TreeMap<>();
    //每个真是节点虚拟出5个虚拟节点
    private static final int VIRTUAL_NODES = 5;

    //初始化时，创建好真是节点 和 所有的虚拟节点
    static {
        for (int i = 0, length = servers.length; i < length; i++) {
            realNodes.add(servers[i]);
        }

        for (String realNode : realNodes) {
            for (int i = 0; i < VIRTUAL_NODES; i++) {
                String virtualNodeName = realNode + "&&VN" + i;
                Integer virtualNodeKey = getHash(virtualNodeName);
                virtualNodes.put(virtualNodeKey, virtualNodeName);
            }
        }
    }

    //使用FNV1_32_HASH算法计算服务器的Hash值,这里不使用重写hashCode的方法，最终效果没区别
    private static int getHash(String str) {
        final int p = 16777619;
        int hash = (int) 2166136261L;
        for (int i = 0; i < str.length(); i++)
            hash = (hash ^ str.charAt(i)) * p;
        hash += hash << 13;
        hash ^= hash >> 7;
        hash += hash << 3;
        hash ^= hash >> 17;
        hash += hash << 5;

        // 如果算出来的值为负数则取其绝对值
        if (hash < 0)
            hash = Math.abs(hash);
        return hash;
    }

    public static String getServer(String key) {
        Integer targetHash = getHash(key);
        SortedMap<Integer, String> subMap = virtualNodes.tailMap(targetHash);
        String virtualNode;
        if (subMap.isEmpty()) {
            Integer i = virtualNodes.firstKey();
            virtualNode = virtualNodes.get(i);
        } else {
            Integer i = subMap.firstKey();
            virtualNode = subMap.get(i);
        }

        if (virtualNode != null && virtualNode.length() > 0) {
            return virtualNode.substring(0, virtualNode.indexOf("&&"));
        }

        return null;
    }

    public static void main(String[] args) {
        String[] keys = {"香蕉111adf阿斯蒂芬", "菠萝222", "蜂蜜333发顺丰"};

        for (int i = 0; i < keys.length; i++) {
            System.out.println("[" + keys[i] + "]的hash值为" +
                    getHash(keys[i]) + ", 被路由到结点[" + getServer(keys[i]) + "]");
        }

        /*TreeMap<Integer, String> treeMap = new TreeMap<>();
        treeMap.put(3, "3");
        treeMap.put(5, "5");
        treeMap.put(1, "1");

        SortedMap<Integer, String> subMap = treeMap.tailMap(2);
        Set<Integer> keySet = subMap.keySet();
        for (Integer key : keySet) {
            System.out.println(subMap.get(key));
        }*/
    }
}
